<!--
  -- 描述：字典选择菜单
  --
  -- 作者：cyq
-->
<template>
  <div style="background: #f2f6fc;
    padding: 0 5px;">
    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
    <div style="margin: 15px 0;"></div>
    <el-checkbox-group v-model="checked" @change="handleCheckedChange">
      <el-checkbox v-for="item in list" :label="item.id" :key="item.id">{{item.text}}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script>
  export default {
    name: "DictionaryCheckbox",
    model: {
      prop: 'mval',
      event: 'modelValue'
    },
    props: ['mval','parentCode'],
    watch: {
      mval: {
        handler() {
          if(this.mval) {
            this.checked = this.mval.split(',');
            this.checkAllStatus();
          }
        },
        immediate: true,
        deep: true
      }
    },
    mounted: function() {
      this.api.post('/bucket-system/system/dict/all', {'code': this.parentCode})
        .then((data) => {
          this.list = data.data;
          this.checkAllStatus();
        });
    },
    data() {
      return {
        list: [],
        checked: [],
        checkAll: false,
        isIndeterminate: false
      }
    },
    methods: {
      selectHandler(){
        this.$emit('modelValue', this.checked.join(','))
      },
      handleCheckAllChange(val) {
        let list = [];
        this.list.forEach((item) => {
          list.push(item.id);
        });
        this.checked = val ? list : [];
        this.isIndeterminate = false;
        this.selectHandler();
      },
      handleCheckedChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.list.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.list.length;
        this.selectHandler();

      },
      checkAllStatus() {
        let checkedCount = this.checked.length;
        this.checkAll = checkedCount === this.list.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.list.length;
      }
    }
  }
</script>

